package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class LockUtil implements ILock{
    private StringRedisTemplate stringRedisTemplate;
    private String key;
    private  final static String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private String value;
    private final static String KEY_PREFIX = "lock:";
    private final static DefaultRedisScript<Long> REDIS_SCRIPT;
    public LockUtil(StringRedisTemplate stringRedisTemplate,String key,String value) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.key = key;
        this.value = value;
    }
static{
    REDIS_SCRIPT = new DefaultRedisScript();
    REDIS_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
    REDIS_SCRIPT.setResultType(Long.class);

}
    @Override
    public boolean tryLock(long expireTime) {
        String  threadId = ID_PREFIX+value;
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + key, threadId, expireTime, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock() {
//        String  threadId = ID_PREFIX+value;
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + key);
//        if(threadId != null && threadId.equals(id)){//相等才删除
//            stringRedisTemplate.delete(KEY_PREFIX + key);
//        }
        stringRedisTemplate.execute(REDIS_SCRIPT,
                Collections.singletonList(KEY_PREFIX + key),
                ID_PREFIX+value);
    }
}
